package com.kermel.andromeda.activities.alarm.view;

import java.text.DateFormat;
import java.util.Date;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kermel.andromeda.R;
import com.kermel.andromeda.data.Alarm;

public class AlarmView extends LinearLayout implements OnCheckedChangeListener {
    private Alarm alarm;
    private TextView alarmNameLabel;
    private TextView alarmTimeLabel;
    private CheckBox alarmEnabledInput;
    private DateFormat dateFormat;
    
    public AlarmView(Context context, Alarm alarm) {
        super(context);
        this.alarm = alarm;

        setHapticFeedbackEnabled(true);
        
        inflateAndAddAlarmView();
        initDateFormat();
        storeWidgetHandles();
        initListeners();
        
        updateViewWithDataFromAlarm();
    }
    
    private void inflateAndAddAlarmView() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View alarmWidget = inflater.inflate(R.layout.alarm_view, null);
        addView(alarmWidget);
    }
    
    private void initDateFormat() {
        dateFormat = android.text.format.DateFormat.getTimeFormat(getContext());
    }
    
    private void storeWidgetHandles() {
        alarmNameLabel = (TextView)findViewById(R.id.alarmViewAlarmNameLabel);
        alarmTimeLabel = (TextView)findViewById(R.id.alarmViewAlarmTimeLabel);
        alarmEnabledInput = (CheckBox)findViewById(R.id.alarmViewAlarmEnabledInput);
    }
    
    private void initListeners() {
        alarmEnabledInput.setOnCheckedChangeListener(this);
    }
    
    private void updateViewWithDataFromAlarm() {
        alarmNameLabel.setText(alarm.name);
        alarmTimeLabel.setText(dateFormat.format(new Date(alarm.triggerTime)));
        alarmEnabledInput.setChecked(alarm.enabled);
    }
    
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        alarm.enabled = alarmEnabledInput.isChecked();
    }
    
    public void setAlarm(Alarm alarm) {
        this.alarm = alarm;
        updateViewWithDataFromAlarm();
    }
    
    public Alarm getAlarm() {
        return alarm;
    }
}
